package com.hyt.it.ogt.ks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.ks.mapper.ExamCandidateStatusMapper;
import com.hyt.it.ogt.ks.model.dto.ExamCandidateStatusDTO;
import com.hyt.it.ogt.ks.model.entity.ExamCandidateStatus;
import com.hyt.it.ogt.ks.service.IExamCandidateStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author wuyingge
 * @version 1.0.0
 * @ClassName ExamCandidateStatusServiceImpl.java
 * @Description 考生考试过程状态变化
 * @createTime 2023年03月01日 16:26:00
 */
@Slf4j
@Service
public class ExamCandidateStatusServiceImpl extends BaseServiceImpl<ExamCandidateStatusMapper, ExamCandidateStatus>
        implements IExamCandidateStatusService {

    @Resource
    private ExamCandidateStatusMapper examCandidateStatusMapper;

    /**
     * 通过考试id与考生id查询
     * @param examId
     * @param candidateId
     * @return
     */
    public ExamCandidateStatusDTO queryByExamIdAndCandidateId(String examId, String candidateId){
        LambdaQueryWrapper<ExamCandidateStatus> query = Wrappers.<ExamCandidateStatus>lambdaQuery()
                .eq(ExamCandidateStatus::getExamId, examId).eq(ExamCandidateStatus::getCandidateId, candidateId).last("LIMIT 1");

        ExamCandidateStatus entity = this.getOne(query);
        if(Objects.isNull(entity)){
            return null;
        }
        ExamCandidateStatusDTO dto = new ExamCandidateStatusDTO();
        BeanUtils.copyProperties(entity,dto);
        return dto;
    }

    @Override
    public void saveCandidateStatus(List<ExamCandidateStatus> examCandidateStatusList) {
        try {
            examCandidateStatusList.forEach(examCandidateStatus -> {
                if (this.baseMapper.updateCandidateStatus(examCandidateStatus) == 0) {
                    try {
                        this.baseMapper.insert(examCandidateStatus);
                    } catch (DuplicateKeyException e) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException interruptedException) {
                            interruptedException.printStackTrace();
                        }
                        this.baseMapper.updateCandidateStatus(examCandidateStatus);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
